import { type Ref, ref, shallowRef, watch } from "vue";
import { getLocalJson, getSessionJson, setLocalJson, setSessionJson } from "@/framework/util/storage";

export function useLocalRef<T>(key: string, value: T): Ref<T>;
export function useLocalRef<T = any>(key: string): Ref<T | undefined>;
export function useLocalRef<T>(key: string, value?: T) {
  const state = ref(getLocalJson(key) ?? value);
  watch(state, v => setLocalJson(key, v));
  return state;
}

export function useLocalShallowRef<T>(key: string, value: T): Ref<T>;
export function useLocalShallowRef<T = any>(key: string): Ref<T | undefined>;
export function useLocalShallowRef<T>(key: string, value?: T) {
  const state = shallowRef(getLocalJson(key) ?? value);
  watch(state, v => setLocalJson(key, v));
  return state;
}

// session

export function useSessionRef<T>(key: string, value: T): Ref<T>;
export function useSessionRef<T = any>(key: string): Ref<T | undefined>;
export function useSessionRef<T>(key: string, value?: T) {
  const state = ref(getSessionJson(key) ?? value);
  watch(state, v => setSessionJson(key, v));
  return state;
}

export function useSessionShallowRef<T>(key: string, value: T): Ref<T>;
export function useSessionShallowRef<T = any>(key: string): Ref<T | undefined>;
export function useSessionShallowRef<T>(key: string, value?: T) {
  const state = shallowRef(getSessionJson(key) ?? value);
  watch(state, v => setSessionJson(key, v));
  return state;
}
